package com.qf.springboot.controller;


import com.qf.springboot.pojo.User;
import com.qf.springboot.serivce.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class UserController {

    @Autowired
    private UserService userService;
    @RequestMapping("/toLogin")
    public String toLogin(){
        return "login";
    }

    @RequestMapping("/register")
    public String register(){
        return "register";
    }
    /**
     * 跳转到Index页面的方法
     * @return
     */
    @RequestMapping("toIndex")
    public String toIndex(){
        return "index";
    }

    @RequestMapping(value = "login")
    public String login(User user, Model model){
        //封装成请求对象
        UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(), user.getPassword());
        //获取登陆的主体对象
        Subject subject = SecurityUtils.getSubject();
        //登陆
        try{
            subject.login(token);
        }catch (UnknownAccountException err){  //用户名不对

            model.addAttribute("userNameError","用户名不对");
            return "login";
        }catch (IncorrectCredentialsException err){ //说明是密码不对

            model.addAttribute("passwordError","密码不对");
            return "login";
        }catch (Exception err){

            model.addAttribute("otherError","其他问题造成登陆失败");
            return "login";
        }
        //首页要显示用户信息
        //获取用户信息
        //这个方法返回的数据 实际上就是 realm中认证的SimpleAuthticationInfo的第一个参数的数据
        User user1= (User) SecurityUtils.getSubject().getPrincipal();
        model.addAttribute("user",user1);
        return "index";
    }
    //admin角色才能访问
    @RequestMapping("/admin")
    @ResponseBody
    public String admin() {
        return "admin success";
    }

    //有delete权限才能访问
    @RequestMapping("/edit")
    @ResponseBody
    public String edit() {
        return "edit success";
    }

    @RequestMapping("/test")
    @ResponseBody
    @RequiresRoles("guest")
    public String test(){
        return "test success";
    }
    //注册用户
    @RequestMapping(value = "Register")
    public String inster(User user){
        userService.insert(user);
        return "index";
    }
}
